package com.framework.websocket.core;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket 订阅配置中心
 * 管理所有的订阅类型和 Redis 键前缀的映射关系
 */
@Component
@ConfigurationProperties(prefix = "websocket")
@Getter
@Setter
public class SubscriptionConfig {
    
    /**
     * 订阅类型定义
     */
    public static final String TYPE_DEVICE_STATUS = "DEVICE_STATUS";
    public static final String TYPE_ALARM = "ALARM";
    public static final String TYPE_SYSTEM_NOTIFY = "SYSTEM_NOTIFY";
    public static final String TYPE_USER_MESSAGE = "USER_MESSAGE";
    
    /**
     * Redis 键前缀定义
     */
    public static final String PREFIX_DEVICE_STATUS = "device:status:";
    public static final String PREFIX_ALARM = "alarm:";
    public static final String PREFIX_SYSTEM = "system:notify:";
    public static final String PREFIX_USER_MSG = "user:message:";
    
    /**
     * 订阅类型到键前缀的映射
     * 可以通过配置文件覆盖
     */
    private Map<String, String> typeToPrefixMap = new HashMap<String, String>() {{
        put(TYPE_DEVICE_STATUS, PREFIX_DEVICE_STATUS);
        put(TYPE_ALARM, PREFIX_ALARM);
        put(TYPE_SYSTEM_NOTIFY, PREFIX_SYSTEM);
        put(TYPE_USER_MESSAGE, PREFIX_USER_MSG);
    }};
    
    /**
     * 订阅类型的描述信息
     */
    private Map<String, String> typeDescriptions = new HashMap<String, String>() {{
        put(TYPE_DEVICE_STATUS, "设备状态变更通知");
        put(TYPE_ALARM, "告警信息推送");
        put(TYPE_SYSTEM_NOTIFY, "系统通知消息");
        put(TYPE_USER_MESSAGE, "用户消息推送");
    }};
    
    /**
     * 心跳配置
     */
    private HeartbeatConfig heartbeat = new HeartbeatConfig();
    
    @Getter
    @Setter
    public static class HeartbeatConfig {
        private long interval = 30000; // 心跳间隔，默认30秒
        private long timeout = 90000;  // 心跳超时，默认90秒
    }
    
    /**
     * 根据订阅类型获取键前缀
     */
    public String getKeyPrefix(String subscriptionType) {
        return typeToPrefixMap.get(subscriptionType);
    }
    
    /**
     * 根据键前缀查找订阅类型
     */
    public String getSubscriptionType(String key) {
        for (Map.Entry<String, String> entry : typeToPrefixMap.entrySet()) {
            if (key.startsWith(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }
    
    /**
     * 判断是否为有效的订阅类型
     */
    public boolean isValidSubscriptionType(String type) {
        return typeToPrefixMap.containsKey(type);
    }
    
    /**
     * 注册新的订阅类型
     */
    public void registerSubscriptionType(String type, String keyPrefix, String description) {
        typeToPrefixMap.put(type, keyPrefix);
        typeDescriptions.put(type, description);
    }
}